package cn.jinjimi.app.controller;

import android.text.TextUtils;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;

import java.util.concurrent.Callable;

import bolts.Continuation;
import bolts.Task;
import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.controller.event.LogoutEvent;
import cn.jinjimi.domain.data.dto.BaseResDto;
import cn.jinjimi.domain.data.dto.TokenDto;
import cn.jinjimi.domain.data.net.API;
import cn.jinjimi.domain.data.net.AuthService;
import retrofit2.Call;
import retrofit2.Response;

/**
 *
 * @author zhenhua
 * @date 2018/1/28
 */

public class AccountController {
    public static Task<Boolean> getCaptcha(final String mobile) {
        return Task.callInBackground(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                Call<BaseResDto> call = API.create(AuthService.class).getCaptcha(mobile);
                Response<BaseResDto> res = call.execute();
                if (res != null && res.isSuccessful()) {
                    return res.body().result;
                }
                return false;
            }
        });
    }

    public static Task<Boolean> checkLoginState() {
        return Task.callInBackground(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                String token = AccountManager.getInstance().getToken();
                if (!TextUtils.isEmpty(token)) {
                    Response<TokenDto> res = API.create(AuthService.class).checkToken(token).execute();
                    if (res != null && res.isSuccessful()) {
                        TokenDto dto = res.body();
                        if (dto != null) {
                            return !TextUtils.isEmpty(dto.token);
                        }
                    }
                }

                return false;
            }
        }).onSuccess(new Continuation<Boolean, Boolean>() {
            @Override
            public Boolean then(Task<Boolean> task) throws Exception {
                if (!task.getResult()) {
                    AccountController.logout();
                }
                return task.getResult();
            }
        });
    }

    public static void logout() {
        AccountManager.getInstance().logout();
    }
}
